package top.lingkang.finalsession.solon;

import top.lingkang.finalsession.FinalSessionConfig;
import top.lingkang.finalsession.core.FinalRepository;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author lingkang
 * @create by 2024/5/9 17:28
 */
public class MemoryFinalRepositorySolon implements FinalRepository<FinalSessionState> {
    private final ConcurrentMap<String, FinalSessionState> map = new ConcurrentHashMap<>();

    @Override
    public void initConfig(FinalSessionConfig config) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!map.isEmpty()) {
                    long reduce = System.currentTimeMillis() - config.getMaxValidTime() + 300000;// 预留5分钟
                    for (Map.Entry<String, FinalSessionState> entry : map.entrySet()) {
                        if (entry.getValue().getLastAccessedTime() < reduce) {
                            // 淘汰此会话
                            map.remove(entry.getKey());
                        }
                    }
                }
            }
        }, 300000, 14400000);// 4小时执行一次
    }

    @Override
    public FinalSessionState getSession(String id) {
        return map.get(id);
    }

    @Override
    public void setSession(String id, FinalSessionState session) {
        map.put(id, session);
    }

    @Override
    public void deleteSession(String id) {
        map.remove(id);
    }

    @Override
    public void destroy() {

    }
}
